package com.jcsz.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.jcsz.common.constant.SpuConstant;
import com.jcsz.common.to.*;
import com.jcsz.common.to.es.SkuEsModel;
import com.jcsz.common.utils.R;
import com.jcsz.gulimall.product.entity.*;
import com.jcsz.gulimall.product.feign.CouponFeignService;
import com.jcsz.gulimall.product.feign.ProductSaveService;
import com.jcsz.gulimall.product.feign.WareSkuService;
import com.jcsz.gulimall.product.service.*;
import com.jcsz.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcsz.common.utils.PageUtils;
import com.jcsz.common.utils.Query;

import com.jcsz.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private WareSkuService wareSkuService;

    @Autowired
    private ProductSaveService productSaveService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * {
     * page: 1,//当前页码
     * limit: 10,//每页记录数
     * sidx: 'id',//排序字段
     * order: 'asc/desc',//排序方式
     * key: '华为',//检索关键字
     * catelogId: 6,//三级分类id
     * brandId: 1,//品牌id
     * status: 0,//商品状态
     * }
     **/
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> {
                obj.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);


        return new PageUtils(page);

    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //保存spu的基本信息    pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);

        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        this.save(spuInfoEntity);

        //保存spu的描述信息    pms_spu_info_desc

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();

        List<String> spuInfoDesc = spuSaveVo.getDecript();
        if (spuInfoDesc != null && spuInfoDesc.size() > 0) {

            spuInfoDescEntity.setDecript(String.join(",", spuInfoDesc));
            spuInfoDescEntity.setSpuId(spuInfoEntity.getId());

            spuInfoDescService.save(spuInfoDescEntity);
        }

        //保存spu的图片信息    pms_spu_images
        List<String> images = spuSaveVo.getImages();
        if (images != null && images.size() > 0) {
            List<SpuImagesEntity> spuImagesEntities = images.stream().map(obj -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setImgUrl(obj);
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgName(obj.substring(obj.lastIndexOf("_")));
                return spuImagesEntity;
            }).collect(Collectors.toList());

            spuImagesService.saveBatch(spuImagesEntities);
        }

        //保存spu的积分信息    跨库跨表服务调用 sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        if (bounds.getBuyBounds().compareTo(new BigDecimal("0")) == 1 && bounds.getGrowBounds().compareTo(new BigDecimal("0")) == 1) {
            BeanUtils.copyProperties(bounds, spuBoundsTo);
            spuBoundsTo.setSpuId(spuInfoEntity.getId());

            R r = couponFeignService.saveSpuBounds(spuBoundsTo);
            if (!r.get("code").equals(200)) {
                log.info("couponFeignService.saveSpuBounds(spuBoundsTo),保存失败");
            }
        }

        //保存spu基本属性      pms_product_attr_value

        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        if (baseAttrs != null && baseAttrs.size() > 0) {
            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(obj -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(obj.getAttrId());
                productAttrValueEntity.setAttrValue(obj.getAttrValues());
                productAttrValueEntity.setQuickShow(obj.getShowDesc());
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                AttrEntity attrEntity = attrService.getById(obj.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntities);

        }

        //保存sku的基本信息    pms_sku_info
        List<Skus> skusList = spuSaveVo.getSkus();
        if (skusList != null && skusList.size() > 0) {
            skusList.stream().forEach(sku -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSkuDesc(String.join(":", sku.getDescar()));
                skuInfoEntity.setSaleCount(0l);

                List<Images> skuImages = sku.getImages();

                if (skuImages != null && skuImages.size() > 0) {
                    String defaultImg = "";
                    for (Images skuImage : skuImages) {
                        if (skuImage.getDefaultImg() == 1) {
                            defaultImg = skuImage.getImgUrl();
                        }
                    }
                    //没有设置默认图随机返回默认图
                    if (defaultImg.equals("")) {
                        defaultImg = skuImages.stream().findAny().get().getImgUrl();
                    }
                    skuInfoEntity.setSkuDefaultImg(defaultImg);
                }
                skuInfoService.save(skuInfoEntity);
                //保存sku销售属性      pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //保存sku的图片信息    pms_sku_images
                if (skuImages != null && skuImages.size() > 0) {
                    List<SkuImagesEntity> skuImagesEntities = skuImages.stream().filter(img -> !StringUtils.isEmpty(img.getImgUrl())).map(img -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(img, skuImagesEntity);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntities);
                }


                //保存sku的折扣信息    sms_sku_ladder  SkuLadderEntity
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                if (sku.getFullCount() > 0 && sku.getDiscount().compareTo(new BigDecimal("0")) == 1) {
                    skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                    skuLadderTo.setFullCount(sku.getFullCount());
                    skuLadderTo.setDiscount(sku.getDiscount());
                    skuLadderTo.setPrice(sku.getPrice().multiply(sku.getDiscount()));
                    skuLadderTo.setAddOther(sku.getCountStatus());
                    R r1 = couponFeignService.saveSkuLadder(skuLadderTo);
                    if (!r1.get("code").equals(200)) {
                        log.info("couponFeignService.saveSkuLadder(skuLadderTo),保存失败");
                    }
                }

                //保存sku的满减信息    sms_sku_full_reduction
                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                if (sku.getFullPrice().compareTo(new BigDecimal("0")) == 1 && sku.getReducePrice().compareTo(new BigDecimal("0")) == 1) {

                    skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
                    skuFullReductionTo.setFullPrice(sku.getFullPrice());
                    skuFullReductionTo.setReducePrice(sku.getReducePrice());
                    skuFullReductionTo.setAddOther(sku.getPriceStatus());
                    R r2 = couponFeignService.saveSkuFullReduction(skuFullReductionTo);
                    if (!r2.get("code").equals(200)) {
                        log.info("couponFeignService.saveSkuFullReduction(skuFullReductionTo),保存失败");
                    }
                }

                //保存sku的会员价格    sms_member_price
                sku.getMemberPrice().stream().forEach(memberPrice -> {
                    MemberPriceTo memberPriceTo = new MemberPriceTo();
                    if (memberPrice.getPrice().compareTo(new BigDecimal("0")) == 1) {
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberLevelName(memberPrice.getName());
                        memberPriceTo.setMemberLevelId(memberPrice.getId());
                        memberPriceTo.setMemberPrice(memberPrice.getPrice());
                        R save = couponFeignService.saveMemberPrice(memberPriceTo);
                        if (!save.get("code").equals(200)) {
                            log.info("memberPriceService.save(memberPriceTo),保存失败");
                        }
                    }

                });
            });
        }


    }

    /**
     * sup商品上架
     * 往es上架商品不会重复上架，因为上架时指定了skuId
     */
    @Override
    public void upProduct(Long spuId) {
        //根据spuId查出所有的sku
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        //根据spuId获取库存信息

        Map<Long, Boolean> collect = null;

        try {
            List<Long> skuIds = skus.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skuHasStocks = wareSkuService.getSkuHasStocks(skuIds);
            List<SkuHasStockVo> data = skuHasStocks.get("data", new TypeReference<List<SkuHasStockVo>>() {
            });
            collect = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception exception) {
            log.error("远程调用库存服务失败,原因{}", exception);
        }
        //获取属性信息
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        List<Long> attrIds = productAttrValueEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        HashSet<Long> ids = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attr> collectAttrs = productAttrValueEntities.stream().filter(item -> ids.contains(item.getAttrId())).map(obj -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(obj, attr);
            return attr;
        }).collect(Collectors.toList());
        //封装带上传的es数据集合(skuEsModel)
        //遍历sku封装SkuEsModel
        Map<Long, Boolean> stockResult = collect;
        List<SkuEsModel.Attr> searchAttrs = collectAttrs;

        List<SkuEsModel> skuEsModels = skus.stream().map(item -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item, skuEsModel);

            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            skuEsModel.setSkuPrice(item.getPrice());
            /**
             *     private String catalogName;
             *     private String brandName;
             *     private String brandImg;
             **/
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setCatalogName(categoryEntity.getName());

            /**
             *     private Long hotScore;
             *     private Boolean hasStock;
             **/
            skuEsModel.setHotScore(0l);
            //设置库存结果
            skuEsModel.setHasStock(stockResult == null ? false : stockResult.get(item.getSkuId()));
            //设置属性
            skuEsModel.setAttrs(searchAttrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        //调用es模块保存数据
        R r = productSaveService.productStatusUp(skuEsModels);
        if(r.getCode()==200){
            baseMapper.updateSpuStatus(spuId, SpuConstant.PublishStatusEnum.SPU_UP.getCode());
        }else {

        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }


}